import { Context } from 'egg';

export default class CommonUtil {


    /**替换下划线 */
    static replaceUnderLine(val: string, char = '_', first = false) {
        let split = val.split(char).map((p, index) => {
            if (!first && index === 0) {
                return p;
            }
            const arr = p.split("");
            arr[0] = arr[0].toUpperCase();
            return arr.join("");
        });
        return split.join("");
    }

    /**下划线转驼峰 */
    static filterUnderLine(obj: Record<string, any>) {
        const arr = Object.keys(obj).filter(item => item.indexOf("_") !== -1)
        arr.forEach(item => {
            const before = obj[item]
            const key = this.replaceUnderLine(item)
            obj[key] = before
            delete obj[item]
        })
        return obj
    }

    static str2UnderLine(str: string) {
        let arr = str.split("");
        return arr.map(p => {
            if (/[A-Z]/.test(p)) {
                return "_" + p.toLowerCase();
            }
            return p;
        }).join("");
    }

    /**驼峰转下划线 */
    static object2UnderLine(obj: Record<string, any>) {
        const arr = Object.keys(obj);
        const resultObj: Record<string, any> = {};
        arr.forEach(p => {
            console.log(555, this.str2UnderLine(p));
            resultObj[this.str2UnderLine(p)] = obj[p];
        })
        return resultObj;
    }

    /**获取数据 */
    static getRequestData<T = Record<string, any>>(ctx: Context): T {
        let params: Record<string, any>;
        if (ctx.request.headers['request-origion'] === "Knife4j") {
            params = ctx.request.query;
        }
        else {
            if (["get", "delete"].includes(ctx.method.toLowerCase())) {
                params = ctx.request.query;
            }
            else {
                params = ctx.request.body;
            }
        }
        return params as unknown as T;
    }

    /**脚本映射 */
    static typeMapping(type: string) {
        return ['int', 'float'].includes(type) ? "number" : "string";
    }

    static omit<T extends object, K extends keyof T>(obj: T, fields: K[]): Omit<T, K> {
        const clone = { ...obj };
        if (Array.isArray(fields)) {
            fields.forEach(key => {
                delete clone[key];
            });
        }
        return clone;
    }

    static pick<T extends object, K extends keyof T>(obj: T, fields: K[]): Pick<T, K> {
        let resultObj: any = {};
        if (Array.isArray(fields)) {
            fields.forEach(key => {
                resultObj[key] = obj[key];
            });
        }
        return resultObj;
    }
};